/* 
 * MessageGenerator.java      1.00    2008-01-11
 *
 * Copyright (c) 2010 monolist. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information
 * of monolist.  You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the license agreement
 * you entered into with monolist.
 */
package doit.framework.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <pre>
 * system      : 공통
 * menu        : 공통
 * source      : MessageGenerator.java
 * description : message.js 생성
 * </pre> 
 * @version
 * <pre> 
 * 1.0  2008-01-11  monolist  최초 작성
 * 1.1  
 * </pre>
 */

@SuppressWarnings("unchecked")

public class MessageGenerator {
    private static Log logger = LogFactory.getLog(MessageGenerator.class);
	private static String GENERATOR_FILE = "message_ko.properties";
	
	public static void makeMessageJS() {
		Properties properties = new Properties();

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader == null)
			classLoader = MessageGenerator.class.getClassLoader();
		InputStream inputStream = classLoader.getResourceAsStream(GENERATOR_FILE);
		
		try {
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Set keyset = properties.keySet();
		Object[] keys =  keyset.toArray();
		Arrays.sort(keys);
		StringBuffer sb = new StringBuffer();
		
		sb.append("var messageString = new JMap(); \n\n");
		
		for (int i = 0 ; i < keys.length ; i++) {
			if (keys[i].toString().indexOf("/**") < 0 ) { 
				String value = (String)properties.get(keys[i]);
				value = value.replaceAll("\n", "");
				sb.append("messageString.put('"+ keys[i] +"', '" + value + "'); \n");
			}
		}

		File file = new File(classLoader.getResource(GENERATOR_FILE).getFile());
		file = new File(file.getParent());
		file = new File(file.getParent());
		file = new File(file.getParent());
		
		File genFile = null;
		try {
			genFile = new File(file.getPath() + "/script/common/message.js");
			
			if (!genFile.exists()) {
				genFile.createNewFile();
			} else {
				genFile.delete();
				genFile.createNewFile();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
    		RandomAccessFile raf = new RandomAccessFile( genFile, "rw");
    		raf.write((sb.toString() + "\r\n").getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }		
		
        logger.info("Make messge.js : " + genFile.getPath());
	}
}
